<template>
  <div class="employees">
    <div class="page-header">
      <h2 class="page-title">员工管理</h2>
      <p class="page-subtitle">查看、添加、编辑和删除公司的员工信息</p>
    </div>

    <div class="action-bar">
      <el-button type="primary" @click="showAddDialog" class="action-btn">添加员工</el-button>
    </div>

    <div class="content-section">
      <el-table :data="employees" style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="age" label="年龄" />
        <el-table-column prop="gender" label="性别">
          <template #default="{ row }">
            {{ row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="department" label="部门" />
        <el-table-column prop="position" label="职位" />
        <el-table-column prop="salary" label="工资" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="entryTime" label="入职时间">
          <template #default="{ row }">
            {{ row.entryTime ? new Date(row.entryTime).toLocaleString() : '' }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑员工' : '添加员工'"
      width="500px"
      :modal-append-to-body="false"
      :append-to-body="true"
      align-center
      class="employee-dialog"
    >
      <el-scrollbar max-height="60vh">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="employee-form"
        >
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input-number v-model="form.age" :min="18" :max="60" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="部门" prop="department">
            <el-input v-model="form.department" />
          </el-form-item>
          <el-form-item label="职位" prop="position">
            <el-input v-model="form.position" />
          </el-form-item>
          <el-form-item label="工资" prop="salary">
            <el-input-number v-model="form.salary" :min="3000" :max="50000" :precision="2" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
          <el-form-item label="入职时间" prop="entryTime">
            <el-date-picker
              v-model="form.entryTime"
              type="datetime"
              placeholder="选择入职时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="3" />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../utils/request'

const employees = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const form = ref({
  name: '',
  age: 18,
  gender: 1,
  department: '',
  position: '',
  salary: 3000,
  phone: '',
  email: '',
  entryTime: '',
  remark: ''
})

const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { max: 50, message: '姓名长度不能超过50个字符', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 18, max: 60, message: '年龄必须在18-60岁之间', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  department: [
    { required: true, message: '请输入部门', trigger: 'blur' },
    { max: 50, message: '部门长度不能超过50个字符', trigger: 'blur' }
  ],
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' },
    { max: 50, message: '职位长度不能超过50个字符', trigger: 'blur' }
  ],
  salary: [
    { required: true, message: '请输入工资', trigger: 'blur' },
    { type: 'number', min: 3000, max: 50000, message: '工资必须在3000-50000之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  entryTime: [
    { required: true, message: '请选择入职时间', trigger: 'change' }
  ],
  remark: [
    { max: 500, message: '备注长度不能超过500个字符', trigger: 'blur' }
  ]
}

const fetchEmployees = async () => {
  loading.value = true
  try {
    console.log('Fetching employees with params:', {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    
    const response = await request.get('/api/employee/page', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value
      }
    })
    
    console.log('Received response:', response)
    
    if (response.code === 200 && response.data) {
      employees.value = response.data.records || []
      total.value = response.data.total || 0
      console.log('Updated employees:', employees.value)
    } else {
      console.warn('Invalid response:', response)
      employees.value = []
      total.value = 0
      ElMessage.error(response.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('Error details:', {
      message: error.message,
      stack: error.stack,
      response: error.response
    })
    ElMessage.error(error.message || '获取员工列表失败')
    employees.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  isEdit.value = false
  form.value = {
    name: '',
    age: 18,
    gender: 1,
    department: '',
    position: '',
    salary: 3000,
    phone: '',
    email: '',
    entryTime: '',
    remark: ''
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该员工吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await request.delete(`/api/employee/${row.id}`)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        fetchEmployees()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response
        if (isEdit.value) {
          response = await request.put(`/api/employee/${form.value.id}`, form.value)
        } else {
          response = await request.post('/api/employee', form.value)
        }
        
        if (response.code === 200) {
          ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
          dialogVisible.value = false
          fetchEmployees()
        } else {
          ElMessage.error(response.msg || (isEdit.value ? '修改失败' : '添加失败'))
        }
      } catch (error) {
        ElMessage.error(isEdit.value ? '修改失败' : '添加失败')
      }
    }
  })
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchEmployees()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchEmployees()
}

onMounted(() => {
  fetchEmployees()
})
</script>

<style scoped>
.employees {
  max-width: var(--app-max-width);
  margin: 0 auto;
  padding: 0 24px;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-title {
  font-size: 28px;
  font-weight: 500;
  margin-bottom: 12px;
  color: var(--app-text-color);
}

.page-subtitle {
  font-size: 16px;
  color: var(--app-secondary-text);
  max-width: 700px;
  margin: 0 auto;
}

.action-bar {
  margin-bottom: 24px;
  display: flex;
  gap: 12px;
}

.action-btn {
  min-width: 120px;
  height: 40px;
  font-weight: 500;
}

.content-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.employee-form {
  padding: 20px 0;
}

:deep(.employee-dialog) {
  display: flex;
  flex-direction: column;
  margin-top: 8vh;
}

:deep(.el-dialog__body) {
  padding: 20px 24px;
  overflow: visible;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-date-picker) {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-table) {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f8f9fa;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  padding: 20px 24px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

:deep(.el-dialog__footer) {
  padding: 20px 24px;
  border-top: 1px solid var(--el-border-color-lighter);
}
</style> 